package it.gameplanet.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class PersistenceTemplate {

	private final PersistenceManagerFactory pmfInstance;
	private final static Logger log = Logger.getLogger(PersistenceTemplate.class.getName());
	
	public PersistenceTemplate(PersistenceManagerFactory pmfInstance) {
		super();
		this.pmfInstance = pmfInstance;
	}

	public PersistenceTemplate() {
		this(JDOHelper.getPersistenceManagerFactory("transactions-optional"));
	}

	public interface DMLPersistenceManager {
		public void execute(PersistenceManager pm) throws Exception;
	}

	public interface QueryPersistenceManager<T> {
		public List<T> execute(PersistenceManager pm) throws Exception;
	}
	
	public void executeDML(DMLPersistenceManager code) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			code.execute(pm);
		}
		catch(Exception ex) {
			throw new RuntimeException(ex);
		}
		finally {
			closeOrIgnore(pm);		
		}		
	}
	
	public <T> List<T> executeQuery(QueryPersistenceManager<T> code) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			Collection<T> resultDetached = pm.detachCopyAll((List<T>)code.execute(pm));
			
			return new ArrayList<T>(resultDetached);
		}
		catch(Exception ex) {
			throw new RuntimeException(ex);
		}
		finally {
			closeOrIgnore(pm);
		}		
	}
	
	public void closeOrIgnore(PersistenceManager pm) {
		try {
			pm.close();
		}
		catch(Exception e) {
			log.severe(e.getMessage());
		}
	}
	
}
